<template>
  <div>
    <div class="new_font1" >
      <div class="titleHead1">
        产品信息
      </div>
    </div>
    <div>
      <div  v-if="route.query.path != 1">
        <el-form  :disabled="!getDisplay || route.query.path == 1" ref="value_form" :model="productList" class="formData">
          <el-table
            border
            :data="productList"
            height="400px"
          >
            <el-table-column label="序号" align="center" width="80">
              <template #default="props">
                {{props.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column prop="goods_no" align="center"  min-width="200">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  产品编码
                </span>
                <vab-icon
                  v-if="getDisplay"
                  icon="search-line"
                  style="color: #0967f4; margin-left: 12px"
                  @click="look_all"
                />
              </template>
              <template #default="props">
                <el-form-item prop="goods_no">
                  <SelectLoading :clearable="false"  @change="goods_no_change($event,props.row.id)" style="width: 100%" v-model="props.row.goods_no" type="number" :userOrgId="org_id" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="goods_name" align="center" min-width="300">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  产品名称
                </span>
                <vab-icon
                  v-if="getDisplay"
                  icon="search-line"
                  style="color: #0967f4; margin-left: 12px"
                  @click="look_all"
                />
              </template>
              <template #default="props">
                <el-form-item prop="goods_name">
                  <SelectLoading :clearable="false" @change="goods_name_change($event,props.row.id)" style="width: 100%" v-model="props.row.goods_name" type="" :userOrgId="org_id" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="barcode" label="条码" align="center" width="130">
              <template #default="props">
                 <span
                   class="ellipsis"
                   v-text="_FieldFormat(props.row.barcode,  '')"
                 ></span>
              </template>
            </el-table-column>
            <el-table-column prop="spec_name" label="规格型号" align="center"  width="100">
              <template #default="props">
               <span
                 class="ellipsis"
                 v-text="_FieldFormat(props.row.spec_name,  '')"
               ></span>
              </template>
            </el-table-column>
            <el-table-column prop="brand_name" label="品牌" align="center"  width="100">
              <template #default="props">
               <span  class="ellipsis">
                 {{_FieldFormat(props.row.brand_name,  '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="sales_unit" align="center"  width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  销售单位
                </span>
              </template>
              <template #default="props">
                <span  class="ellipsis">
                    <el-form-item prop="sales_unit">
                  <VabSelectForm  :clearable="false" v-if="sales_unit_list?.length >0"  v-model="props.row.sales_unit" :options="sales_unit_list"/>
                </el-form-item>
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="sales_num" align="center"  width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  销售数量
                </span>
              </template>
              <template #default="props">
                <el-form-item prop="sales_num">
                  <el-input-number @change="sales_num_change($event,props.row.id)" :controls='false' type="number" :min="0"   v-model.trim="props.row.sales_num" clearable class="input_many"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="warehouse_no" align="center" width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  仓库
                    <span title="一键填充">
                  <vab-icon @click="warehouseFilling(productList)" class="downIcon" icon="down" is-custom-svg  />
                  </span>
                </span>
              </template>
              <template #default="props">
                <el-form-item prop="warehouse_no">
                  <el-select
                    filterable
                    v-model="props.row.warehouse_no"
                    class="width_100"
                    placeholder="请选择"
                    @change="valueName($event,props.row.id)"
                  >
                    <el-option v-for="item in warehouse_no_list" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                  <!--                  <VabSelectForm @change="valueName('warehouse_no',props.row.id)" :clearable="false"  v-model="props.row.warehouse_no" :options="props.row.warehouse_list"/>-->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="batch_usable_num" label="预计可发量" align="center" width="150">
              <template #default="props">
                 <span class="ellipsis numberMoney">
                    {{_FieldFormat(props.row.batch_usable_num,  '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center" width="150">
              <template #default="props">
                <el-form-item prop="remark">
                  <el-input v-model.trim="props.row.remark"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="80">
              <template #header>
                <span>
                  操作
                </span>
                <vab-icon
                  icon="add-circle-line"
                  class="icon_color"
                  @click="handleClickAddHead"
                />
              </template>
              <template #default="props">
                <vab-icon
                  icon="add-circle-line"
                  class="icon_color"
                  disabled
                  @click="handleClickAdd(props.row)"
                />
                <vab-icon
                  v-if="productList.length>1"
                  icon="delete-bin-5-line"
                  @click="handleClickRemove(props.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <div  v-if="route.query.path == 1">
        <el-table
          border
          :data="productList"
          height="calc(100vh - 560px)"
        >
          <el-table-column label="序号" align="center" width="80">
            <template #default="props">
              {{props.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column prop="goods_no" align="center"  min-width="200">
            <template #header>
              <span>
                  产品编码
                </span>
            </template>
            <template #default="props">
                <span
                  class="ellipsis"
                  v-text="_FieldFormat(props.row.goods_no,  '')"
                ></span>
            </template>
          </el-table-column>
          <el-table-column prop="goods_name" align="center" min-width="300">
            <template #header>
              <span>
                  产品名称
                </span>
            </template>
            <template #default="props">
              <span
                class="ellipsis"
                v-text="_FieldFormat(props.row.goods_name,  '')"
              ></span>
            </template>
          </el-table-column>
          <el-table-column prop="barcode" label="条码" align="center" width="130">
            <template #default="props">
                 <span
                   class="ellipsis"
                   v-text="_FieldFormat(props.row.barcode,  '')"
                 ></span>
            </template>
          </el-table-column>
          <el-table-column prop="spec_name" label="规格型号" align="center"  width="100">
            <template #default="props">
               <span
                 class="ellipsis"
                 v-text="_FieldFormat(props.row.spec_name,  '')"
               ></span>
            </template>
          </el-table-column>
          <el-table-column prop="brand_name" label="品牌" align="center"  width="100">
            <template #default="props">
               <span  class="ellipsis">
                 {{_FieldFormat(props.row.brand_name,  '')}}
               </span>
            </template>
          </el-table-column>
<!--          <el-table-column prop="goods_type" align="center"  width="150">-->
<!--            <template #header>-->
<!--              <span>-->
<!--                  产品类型-->
<!--                </span>-->
<!--            </template>-->
<!--            <template #default="props">-->
<!--                 <span-->
<!--                   class="ellipsis"-->
<!--                   v-text="_FieldFormat(props.row.goods_type,  '')"-->
<!--                 ></span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column prop="sales_unit" align="center"  width="150">
            <template #header>
              <span>
                  销售单位
                </span>
            </template>
            <template #default="props">
                <span  class="ellipsis">
               {{_FieldFormat(props.row.sales_unit,  '')}}
               </span>
            </template>
          </el-table-column>
          <el-table-column prop="sales_num" align="center"  width="150">
            <template #header>
              <span>
                  销售数量
                </span>
            </template>
            <template #default="props">
               <span  class="ellipsis">
               {{_FieldFormat(props.row.sales_num,  '')}}
               </span>
            </template>
          </el-table-column>
          <el-table-column prop="warehouse_no" align="center" width="150">
            <template #header>
              <span>
                  仓库
                </span>
            </template>
            <template #default="props">
               <span  class="ellipsis numberMoney">
                  {{ props.row.warehouse_no && warehouse_no_list?.filter(i=>i.value ==props.row.warehouse_no )[0]?.label || '--'}}
               </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" width="150">
            <template #default="props">
              <span  class="ellipsis ">
                 {{props.row.remark || '--'}}
              </span>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <ProductsAll ref="products_all" v-model:org_id="org_id" />
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import ProductsAll from './ProductsAll.vue'
import SelectLoading from '/@/components/lazySelect/demo.vue'
import _ from 'lodash';
defineOptions({
  name: 'ProductsInQuick',
})
const _FieldFormat = (value: string, type = '') => {
  return FieldFormat(value, type)
}
const route:any = useRoute()
import { Search } from '@element-plus/icons-vue'
import {FieldFormat} from "/@/utils/utils";
import {getProductList, getProductSearch, getProductSearchSelect, productTaxRate} from "/@/api/dms/product";
import {ElMessage} from "element-plus";
import {getInventoryAvailable, getInventoryOrderSearch, getInventorySearchBatch} from "/@/api/dms/inventory";
import { convertToTree, filterateList, flattenArray } from "/@/views/order_management/orderText";
//客户   价目表
const props = defineProps(['copyProductList','copyProductNumber'])
const org_id = ref<any>(undefined)

const getDisplay = ref(props.copyProductNumber && props.copyProductNumber.customer_uid != '' && props.copyProductNumber.customer_uid != undefined && props.copyProductNumber.sales_org_id != '' && props.copyProductNumber.sales_org_id != undefined)
const value_form = ref(null)
const name = ref([])
const number = ref([])
const formRef = ref(null)
const products_all =ref<any>(null)
const products_number = ref<any>([
  {label:'销售数量',item:'sales_num',value: props.copyProductNumber && props.copyProductNumber.sales_num || 0,type:'1'},
  {label:'计价数量',item:'pricing_num',value:props.copyProductNumber && props.copyProductNumber.pricing_num || 0,type:'1'},
  {label:'金额',item:'amount',value:props.copyProductNumber && props.copyProductNumber.amount || 0.00,type:'2'},
  {label:'税额',item:'tax',value:props.copyProductNumber && props.copyProductNumber.tax || 0.00,type:'2'},
  {label:'价税合计',item:'total_amount',value:props.copyProductNumber && props.copyProductNumber.total_amount || 0.00,type:'2'},
  {label:'折后金额',item:'discount_amount',value:props.copyProductNumber && props.copyProductNumber.discount_amount || 0.00,type:'2'},
])
const productList = ref<any>(props.copyProductList && props.copyProductList || [{id:0,price: 0.00,sales_num:0,goods_no:'',batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',goods_type:'样品',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]}])
// **********下拉框选项*****************
const goods_no_list = ref<any>([])
const goods_name_list = ref<any>([])
const goodsNumber = ref<any>([])
const goodsName = ref<any>([])
const goods_type_list = ref([{value:'正品',label:'正品'},{value:'赠品',label:'赠品'},{value:'残次品',label:'残次品'},{value:'样品',label:'样品'}])
const warehouse_no_list = ref([])
const stock_num_list = ref([{value:'1',label:'测试1'}])
// const batch_no_list = ref([{value:'1',label:'测试1'}])
const expire_date_list  = ref([])
const tax_rate_list =  ref([])
const taxRate = ref<any>([])
// 销售单位
const sales_unit_list = ref([])
//*********仓库一键填充**************
const warehouseFilling = async (va:any)=>{
  const warehouseArray = va
  const fillingOrder:any = warehouseArray.filter((i:any)=> i.goods_no !== '' && i.goods_name !==''&& i.warehouse_no !=='')|| []
  if(fillingOrder.length >0){
    productList.value =await Promise.all( warehouseArray.map( async(item:any)=>{
        if(item.goods_type !==''&& item.goods_no !== '' && item.goods_name !==''&& item.warehouse_no ==''){
          let list:any = await getOrd(item.goods_no,fillingOrder[0]?.warehouse_no,item.batch_no,item.expire_date)
          return {
            ...item,
            warehouse_no:fillingOrder[0]?.warehouse_no,
            batch_usable_num:Number(list.available_num).toFixed(0),
          }
        }else {
          return item
        }
      })
    )
  }
}
// **********查询 模糊******************
// 存储总数据
const arrList = ref<any>([])
const numberChang = async (va:any)=>{
  page.value = 1
  goodsNumber.value = []
  arrList.value = []
  if(va){
    await getPriceList(org_id.value,'',va)
  }else {
    // hasMore.value = true
    await getPriceList(org_id.value,"",'')
  }
  await getPriceList(org_id.value,'',va.trim())
}
const nameChang = async (va:any)=>{
  page.value = 1
  goodsName.value = []
  arrList.value = []
  if(va){
    await getPriceList(org_id.value,va.trim(),'')
  }else {
    // hasMore.value = true
    await getPriceList(org_id.value,"",'')
  }
}
// ********添加产品*************
const handleClickAdd =(row:any)=>{
  const newObject = {id:String(new Date().getTime()).slice(-6), price: 0.00,sales_num:0,goods_no:'',batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',goods_type:'',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]}
  const insertIndex = productList.value.findIndex((item:any)=> item.id === row.id) + 1;
  productList.value.splice(insertIndex, 0, newObject)
  // productList.value.push({id:String(new Date().getTime()).slice(-6),sales_num:0,goods_no:'',batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',goods_type:'',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]})
}
// 头部添加产品
const handleClickAddHead =()=>{
  const newObject = {id:String(new Date().getTime()).slice(-6),price_remark:'',price:0.00,sales_num:0,goods_no:'',batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',goods_type:'',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]}
  productList.value.splice(0, 0, newObject)
}
const handleClickRemove = (row:any)=>{
  productList.value =  productList.value.filter((item:any)=>item.id != row.id)
}
//********滚动加载下*************

const page = ref(1)
const loading = ref(false)
const hasMore = ref(true)
const handleLoadMore =_.throttle(async (newPage: number) => {
  if ( !org_id) return
  page.value = await newPage
  await getPriceList(org_id.value)
}, 500)
// *******表格值变化*******
const goods_no_change = async (va:any,id:string|number)=>{
  const arr_list = [...productList.value]
  const arr =  await product_list([va],[])
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      const orderNumber:any = (arr[0].retail_price/(1+Number(arr[0].tax_rate )/100)).toFixed(6)
      return {
        ...item,
        sales_unit:arr[0].unit_name,// 销售单位
        goods_no:arr[0].number,//产品编码
        goods_name: arr[0].name,//产品名称
        // spec_no:'',//商家编码
        barcode:arr[0].barcode || '',// 条码
        spec_name:arr[0].specification,//规格名称
        brand_name:arr[0].assistant_name,//品牌
        // order_price:orderNumber,//单价
        price:arr[0].retail_price || 0.00,//价目表单价
        order_price:0, //单价
        // including_tax_price:arr[0].retail_price, //含税单价
        including_tax_price:0,
        tax_rate:arr[0].tax_rate, //税率
        tax:0.00, // 税额
        total_amount:0.00, //价税合计
        warehouse_no:'', //仓库编号
        warehouse_name:'', //仓库编号
        stock_org_name:'',//库存组织名称
        settle_org_name:'',//结算组织
        amount:0.00,// 金额
        sales_num:0,//销售数量
        goods_type:'样品', // 产品类型
        batch_no:'',//批次号
        expire_date:'',//效期
        batch_usable_num:0,//预计可发量
        batch_no_list: arr[0].stock_batch?.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}}),
        raw_data:arr[0],
      }
    }else {
      return item
    }
  })
  // countNumber(productList.value)
}
const goods_name_change= async (va:any,id:string|number)=>{
  const arr_list = [...productList.value]
  const arr =  await product_list([va],[])
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      const orderNumber:any = (arr[0].retail_price/(1+Number(arr[0].tax_rate )/100)).toFixed(6)
      return {
        ...item,
        sales_unit:arr[0].unit_name,// 销售单位
        goods_no:arr[0].number,//产品编码
        goods_name: arr[0].name,//产品名称
        // spec_no:'',//商家编码
        barcode:arr[0].barcode || '',// 条码
        spec_name:arr[0].specification,//规格名称
        brand_name:arr[0].assistant_name,//品牌
        // order_price:orderNumber, //单价
        price:arr[0].retail_price || 0.00,//价目表单价
        order_price:0, //单价
        // including_tax_price:arr[0].retail_price, //含税单价
        including_tax_price:0,
        tax_rate:arr[0].tax_rate, //税率
        tax:0.00, // 税额
        total_amount:0.00, //价税合计
        warehouse_no:'', //仓库编号
        warehouse_name:'', //仓库编号
        stock_org_name:'',//库存组织名称
        settle_org_name:'',//结算组织
        amount:0.00,// 金额
        sales_num:0,
        remark:'',
        goods_type:'样品', // 产品类型
        batch_no:'',//批次号
        expire_date:'',//效期
        batch_usable_num:0,//预计可发量
        batch_no_list:arr[0].stock_batch?.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}}),
        raw_data:arr[0],
      }
    }else {
      return item
    }
  })
  // countNumber(productList.value)
}
const valueName =async (value:string,id:string|number)=>{
  const arr_list = [...productList.value]
  const arrId = arr_list.filter((i:any)=>i.id == id)[0]
  if(arrId.goods_no !== '' && arrId.goods_no !== undefined && arrId.goods_no!== null){
    let list:any = await getOrd(arrId.goods_no,arrId.warehouse_no,arrId.batch_no,arrId.expire_date)
    let listNumber:any = await batchNoList(arrId.goods_no,arrId.warehouse_no,arrId.expire_date)
    let batch = listNumber.find((i:any)=>i.value == arrId.batch_no)
    productList.value = arr_list.map((item:any)=>{
      if(item.id == id && item.goods_no!= ''&& item.warehouse_no!='' ){
        return {
          ...item,
          batch_usable_num:Number(list.available_num).toFixed(0),
        /*  stock_org_name:list.stock_org?.organization_name,
          settle_org_name:list.settle_org?.organization_name,
          batch_no_list:listNumber,
          batch_no:batch && batch.value||'',*/
        }
      }else {
        return item
      }
    })
  }
}
const countNumber = (arr_list:any)=>{
  const pricing = arr_list.map((num:any)=> {if(num.goods_type !== '赠品'&& num.goods_type !== '样品'){return Number(num.sales_num) }else {return 0}} ).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const total_amount = arr_list.map((num:any)=> Number( num.total_amount)).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const amount = arr_list.map((num:any)=> Number( num.amount)).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const taxList = arr_list.map((num:any)=> Number( num.tax)).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const salesNumber = arr_list.map((num:any)=> num.sales_num).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  products_number.value =  products_number.value.map((i:any)=>{
    if(i.item == 'sales_num'){
      return {
        ...i,
        value: Number(salesNumber),
      }
    }else if(i.item == 'pricing_num'){
      return {
        ...i,
        value:  isNaN(pricing) ? 0: Number(pricing)
      }
    }else if(i.item == 'total_amount'){
      return {
        ...i,
        value: Number(total_amount).toFixed(2)
      }
    } else if(i.item == 'amount'){
      return {
        ...i,
        value: Number(amount).toFixed(2)
      }
    } if(i.item == 'tax'){
      return {
        ...i,
        value: Number(taxList).toFixed(2)
      }
    }else {
      return  i
    }
  })
}
// 销售数量
const sales_num_change = (va:any,id:string|number)=>{
  productList.value = productList.value.map((item:any)=>{
    if(item.id == id){
      const numb = Number(item.tax_rate)/100
      // 含税价
      const order:any =  (item.including_tax_price/(1+ numb)).toFixed(6) || 0.000000
      // 税额
      const taxNumber =  (order * numb * Number(va)).toFixed(2) || 0.00
      // 不含税金额
      const amountNumber = (order*va).toFixed(2) || 0.00
      // 含税金额
      const totalAmountNumber =  (item.including_tax_price * va ).toFixed(2)|| 0.00
      return {
        ...item,
        order_price:order,
        tax: taxNumber ,
        amount:amountNumber,
        total_amount:totalAmountNumber,
      }
    }else {
      return{
        ...item
      }
    }
  })
  // countNumber(productList.value)
}
// 含税单价
const order_price_change =  (va:any,id:string|number)=>{
  const arr_list = [...productList.value]
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      const numb = Number(item.tax_rate)/100
      // 不含税价
      const order:any =(va/(1+ numb)).toFixed(6) || 0.000000
      // 税额
      const taxNumber =(order * numb * Number(item.sales_num || 0)).toFixed(2) || 0.00
      // 不含税金额
      const amountNumber =  ( order*Number(item.sales_num)).toFixed(2) || 0.00
      // 含税金额
      const totalAmountNumber =  ( Number(item.sales_num || 0) * va).toFixed(2) || 0.00
      return {
        ...item,
        tax: taxNumber,
        order_price:order,
        amount: amountNumber,
        total_amount:totalAmountNumber,
      }
    }else {
      return{
        ...item
      }
    }
  })
  // countNumber(productList.value)
}
// 税率
const taxRateChange = (value:any,id:string|number)=>{
  const numb = Number(value)/100
  const   num = 1+ numb
  const arr_list = [...productList.value]
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      // 不含税价
      const order:any =  (item.including_tax_price/num).toFixed(6) || 0.000000
      // 税额
      const taxNumber = (order * numb * item.sales_num).toFixed(2) || 0.00
      // 不含税金额
      const amountNumber =  (order*item.sales_num).toFixed(2) || 0.00
      // 含税金额
      // const totalAmountNumber = va && va != 0 ?( Number(item.sales_num || 0) * va).toFixed(2) : 0.00
      return {
        ...item,
        tax: taxNumber,
        order_price:order,
        amount:amountNumber,
      }
    }else {
      return{
        ...item
      }
    }
  })
  // countNumber(productList.value)
}

// 查看全部产品
const look_all = ()=>{
  products_all.value.dialogVisibles = true
}
// 查询
const query = async ()=>{
  if(number.value.length > 0 || name.value.length>0){
    const arr = await product_list(number.value,name.value)
    ElMessage.success('查询成功')
    productList.value = [...productList.value,...arr_map(arr)]
  }else {
    ElMessage.warning('查询内容不能为空')
  }

}
const arr_map= (arr:any)=>{
  const arr_1 = arr.map((value:any,index:number)=>{
    const orderNumber:any = (value.retail_price/(1+Number(value.tax_rate )/100)).toFixed(6)
    return{
      goods_no:value.number,//产品编码
      goods_name: value.name,//产品名称
      // spec_no:'',//商家编码
      barcode:value.barcode,// 条码
      spec_name:value.specification,//规格名称
      brand_name:value.assistant_name,//品牌
      goods_type:'样品', // 产品类型
      sales_unit:value.unit_name, //销售单位
      sales_num:0,  //销售数量
      // order_price:orderNumber, //单价
      price:value.retail_price||0.00,
      order_price:0, //单价
      // including_tax_price:value.retail_price, //含税单价
      including_tax_price:0,
      tax_rate:value.tax_rate, //税率
      tax:0.00, // 税额
      total_amount:0.00, //价税合计
      warehouse_no:'', //仓库编号
      warehouse_name:'', //仓库编号
      stock_org_name:'',//库存组织名称
      settle_org_name:'',//结算组织
      amount:0.00,// 金额
      remark:'',
      raw_data:value,
      batch_no:'',//批次号
      expire_date:'',//效期
      batch_usable_num:0,//预计可发量
      batch_no_list:value.stock_batch?.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}}),
      id:String(new Date().getTime()).slice(-6) + index ,
    }
  })
  return arr_1
}
const product_list = async (number_list:any,name_list:any)=>{
  let arr = await getProductList({page:1,limit:500,type:1,filter:{number:number_list || [],name:name_list || [],use_org_id:org_id.value}})
  return arr.data.list
}
// 获取产品 名称  编码
const all_date = ref<any>([])
// 通过产品id 仓库名称 获取销售组织 结算组织
const getOrd= async (uid:number|string,ownerId:number|string,batchId='',expireId='')=>{
  if(uid != ''&& ownerId !== '' ){
    let arr:any = await getInventoryAvailable({spec_no:uid,owner_no:ownerId,batch_no:batchId,expire_day:expireId})
    return arr.data
  }else {
    return {}
  }
}
//动态获取批次号
const batchNoList = async (spec_no:number|string,owner_no:number|string,expire_day:number|string,)=>{
  if(spec_no !='' && spec_no){
    let arr = await getInventorySearchBatch({spec_no:spec_no,owner_no:owner_no,expire_day:expire_day})
    return arr.data.list.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}})
  }else {
    return {}
  }
}
const _GetProductSearch = async () => {
  try {
    const res = await getProductSearch()
    const tax = await productTaxRate({})
    res.data.brand.push({ entry_id: '', name: '空' })
    res.data.class_one.push({ id: '', data_title: '空' })
    res.data.class_two.push({ id: '', data_title: '空' })
    res.data.series.push({ id: '', data_title: '空' })
    res.data.category.push({ id: '', data_title: '空' })
    all_date.value = res.data
    taxRate.value = tax.data
  } catch (error) { }
}
//通过价目表获取产品
const getPriceList = (id:any,name='',number='')=>{
  loading.value = true
  if(id){
    getProductSearchSelect({page:page.value, limit:100,filter:{use_org_id:id,name:name,number:number}}).then((data:any)=>{
      if(data.code == 200){
        loading.value = false
        arrList.value=[...arrList.value,...data.data.list]
        goods_no_list.value = [...goods_no_list.value,...data.data.list?.map((i:any)=> {return {value:i.number,label:i.number}})]
        goods_name_list.value = [...goods_name_list.value,...data.data.list?.map((i:any)=> {return {value:i.name,label:i.name}})]
        goodsNumber.value =  [...goodsNumber.value,...data.data.list?.map((i:any)=> {return {value:i.number,label:i.number}})]
        goodsName.value = [...goodsName.value,...data.data.list?.map((i:any)=> {return {value:i.name,label:i.name}})]
        hasMore.value =  arrList.value.length < data.data.count
      }
    })
  }
}
onMounted(()=>{
  _GetProductSearch()
  products_all.value.type = 2
})
watchEffect(()=>{
  const { multipleList } = products_all.value || []
  if( multipleList ){
    const arr = [...multipleList]
    productList.value = [...filterateList(productList.value),...arr_map(arr)]
    products_all.value.multipleList = undefined
  }
  tax_rate_list.value = taxRate.value.tax_rate?.map((i:any)=> {return {value:i.tax_rate,label:i.rate_name}})
  sales_unit_list.value = taxRate.value.unit?.map((i:any)=> {return {value:i.name,label:i.name}})
  warehouse_no_list.value = taxRate.value.wms_owner?.map((i:any)=> {return {value:i.owner_no,label:i.short_name}})
  expire_date_list.value = taxRate.value.expire_list?.map((i:any)=> {return {value:String(i.day),label:i.name}})
  getDisplay.value = props.copyProductNumber && props.copyProductNumber.customer_uid != ''&& props.copyProductNumber.customer_uid != undefined && props.copyProductNumber.sales_org_id != '' && props.copyProductNumber.sales_org_id != undefined
  // countNumber(productList.value)
  org_id.value = props.copyProductNumber && props.copyProductNumber.sales_org_id || undefined
})
watch(props.copyProductNumber,()=>{
  // 获取组织uid
  org_id.value = props.copyProductNumber && props.copyProductNumber.sales_org_id || undefined
  if(org_id){
    getPriceList(org_id.value)
  }
})
//抛出数据
defineExpose({
  productList,
  products_number,
})
</script>

<style lang="scss" scoped>
@import "../index";
</style>

